package juc;

/**
 * @author liweimin
 * @date 2021/1/18 19:55
 * @description volatile 测试
 * @since
 */
public class TestVolatile {
    public static void main(String[] args) {
        ThreadDemo td = new ThreadDemo();
        new Thread(td).start();
        while (true) {
            //while(true) 较底层 先执行
//            synchronized (td){
            if (td.isFlag()) {
                System.out.println("======================================");
                //flag已经在ThreadDemo中改变了值，但是main线程没发现
                break;
            }

//            }
        }
    }
}

class ThreadDemo implements Runnable {

    //    private boolean flag = false;
    private volatile boolean flag = false;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }


    @Override
    public  void run() {
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = true;
        System.out.println("flag=" + isFlag());
    }
}